from django.db.models import F
from django.shortcuts import render

from rest_framework.generics import RetrieveAPIView
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response

from apps.publish.models import PublishModel
from apps.Detail.serializers import PublishDetailModelSerializer,CommentModelSerializer,CreateCommentModelSerializer,FavorModelSerializer
from apps.Detail.models import CommentRecordModel
from apps.login.models import UserInfo
from apps.Detail.models import ViewerRecordModel,FavorRecordModel

from scripts.auth import GeneralAuthentication,UserAuthentication

# 文章详情页
# RetrieveAPIView 只取一条数据 处理的是GET请求
class PublishDetailsView(RetrieveAPIView):
    queryset = PublishModel.objects
    serializer_class = PublishDetailModelSerializer
    # authentication_classes = [GeneralAuthentication]

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        # 去 Authorization 请求中获取token  HTTP_XXX 必须大写
        # 如果用户已经登录，添加访客记录

        token = request.META.get('HTTP_AUTHORIZATION',None)
        print(f"获取的token：{token}")
        if not token:
            return response
        user_object = UserInfo.objects.filter(token=token).first()
        if not user_object:
            return response

        # 再访客记录中添加记录
        # 判断当前用户是否已经访问

        if not request.user:
            return response

        # article_object = self.get_object()
        print(request.user)
        pk = int(kwargs.get('pk'))
        print(f"pk:{pk},{type(pk)}")
        exists = ViewerRecordModel.objects.filter(user=user_object,article_id=pk).exists()
        if exists:
            return response
        ViewerRecordModel.objects.create(user=request.user,article_id=pk)
        PublishModel.objects.filter(id=pk).update(viewer_count=F("viewer_count")+1)


        return response


# 评论视图
class CommentView(APIView):

    # 重写
    def get_authenticators(self):
        if self.request.method == "POST":
            return [UserAuthentication(),]
        return [GeneralAuthentication(),]

    def get(self,request):
        # 获取根评论id
        root_id = request.query_params.get("root")

        # 获取该根评论id下的子评论
        node_queryset = CommentRecordModel.objects.filter(root_id=root_id).order_by("id")

        # 反序列化
        ser = CommentModelSerializer(instance=node_queryset,many=True)

        return Response(ser.data,status=status.HTTP_200_OK)

    def post(self, request):
        print(request.data)
        # 进行数据校验
        ser = CreateCommentModelSerializer(data=request.data)
        # 验证通过，保存到数据库 ser.data 获取序列化的数据
        if ser.is_valid():
            ser.save(user_id=1)

            publish_id = ser.data.get("article")
            PublishModel.objects.filter(id=publish_id).update(comment_count=F("comment_count") + 1)

            return Response(ser.data, status=status.HTTP_201_CREATED)
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)

        # 将保存到数据库的数据返回给小程序页面



# 点赞视图
class FavorView(APIView):
    authentication_classes = [UserAuthentication,]
    def post(self,request):
        print(request.data)
        ser = FavorModelSerializer(data=request.data)
        if not ser.is_valid(raise_exception=True):
            return Response({},status=status.HTTP_400_BAD_REQUEST)
        article_object = ser.validated_data.get("article")
        exists = FavorRecordModel.objects.filter(user=request.user,article=article_object).exists()
        if exists:
            FavorRecordModel.objects.filter(user=request.user,article=article_object).delete()
            return Response({},status=status.HTTP_200_OK)
        FavorRecordModel.objects.create(user=request.user, article=article_object)
        return Response({},status=status.HTTP_201_CREATED)

